const connection = require("../app/database");
const { to } = require("../utils");

class FileService {
    async uploadAvatar(filename, mimetype, size, userId) {
        const statement = `INSERT INTO file (filename,mimetype,size,user_id) values (?,?,?,?)`;
        const [error, resp] = await to(connection.execute(statement, [filename, mimetype, size, userId]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async getAvatarByUserId(id) {
        const statement = "SELECT * FROM file WHERE user_id = ?";
        const [error, resp] = await to(connection.execute(statement, [id]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result.length > 0 ? result.pop() : {};
    }
}

module.exports = new FileService();
